package com.atguigu.flink.chapter08;

import com.atguigu.flink.bean.HotItem;
import com.atguigu.flink.bean.UserBehavior;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeHint;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Comparator;
import java.util.TreeSet;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2022/1/14 8:56
 */
public class Flink03_High_Project_TopN_1 {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);
        // 每隔半个小时, 统计最近1小时的pv
        env
            .readTextFile("input/UserBehavior.csv")
            .map(line -> {
                String[] data = line.split(",");
                return new UserBehavior(
                    Long.valueOf(data[0]),
                    Long.valueOf(data[1]),
                    Integer.valueOf(data[2]),
                    data[3],
                    Long.parseLong(data[4]) * 1000
                
                );
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .filter(ub -> "pv".equals(ub.getBehavior()))
            .keyBy(UserBehavior::getItemId)
            .window(SlidingEventTimeWindows.of(Time.hours(2), Time.minutes(60)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                    
                    @Override
                    public Long add(UserBehavior value, Long acc) {
                        return acc + 1;
                    }
                    
                    @Override
                    public Long getResult(Long acc) {
                        return acc;
                    }
                    
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long itemId,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        Long count = elements.iterator().next();
                        long edt = ctx.window().getEnd();
                        out.collect(new HotItem(edt, itemId, count));
                        
                    }
                }
            )
            .keyBy(HotItem::getEdt)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
                
                private ValueState<TreeSet<HotItem>> treeSetState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    treeSetState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<TreeSet<HotItem>>("treeSetState", TypeInformation.of(new TypeHint<TreeSet<HotItem>>() {})));
                }
                
                @Override
                public void processElement(HotItem value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 向状态中村数据的时候, 只存最大的三个,
                    // TreeSet 自动排序
                    // 状态中可以存储一个TreeSet(可以自动排序)集合, 集合中只保留最大的三个
                    TreeSet<HotItem> set = treeSetState.value();
                    if (set == null) {
                        set = new TreeSet<>(new Comparator<HotItem>() {
                            @Override
                            public int compare(HotItem o1, HotItem o2) {
                                int i = o2.getCount().compareTo(o1.getCount());
                                return i == 0 ? 1 : i;
                            }
                        });
                        treeSetState.update(set);
    
                        ctx.timerService().registerEventTimeTimer(value.getEdt() + 2000);
                    }
                    
                    set.add(value);  // set集合会自动排序, 如果大于3把最小的删掉
                    if (set.size() > 3) {
                        set.pollLast();// 删除最后一个元素
                    }
                    
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    TreeSet<HotItem> set = treeSetState.value();
    
                    String msg = "-------------------\n";
                    for (HotItem hotItem : set) {
                        msg += hotItem + "\n";
                    }
                    out.collect(msg);
                    
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
